<template>
    <div class="main">
        <div class="top_box" style="margin-top:15px">
            <el-input style="width:200px" placeholder="收费站/服务区名称/路段名称" v-model="keyword"></el-input>
            <!-- <el-cascader style="width:200px;margin-left:20px" ref="cascader" v-model="admin_id" :props="props" clearable
                placeholder="请选择管理中心/路段"></el-cascader> -->
            <div style="width:200px;margin-left:10px" v-if="!(role==18||role==19)">
                <el-select v-model="admin_id" placeholder="请选择管理中心">
                    <el-option v-for="item in adminUser" :key="item.id" :label="item.nickname" :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <el-button type="warning" style="margin-left:20px" icon="el-icon-search" size="small" @click="getInfo">搜索</el-button>
            <el-button style="margin-left:20px" size="small" @click="reset " type="primary">重置</el-button>
            <el-button type="warning" icon="el-icon-plus" style="margin-left:20px" size="small" @click="add">添加单位</el-button>
            <el-button type="primary" style="margin: 0 10px;" @click="importTemplate">下载导入模板</el-button>

            <el-upload-file :showfile="false" v-model="importindex" @change="getImportData()" accept=".xlsx" style="margin: 0 10px;" title="导入"></el-upload-file>
        </div>
        <el-table :data="data" style="width: 100%" border height="100%">
            <el-table-column property="name" label="收费站/服务区名称"></el-table-column>
            <el-table-column property="nickname" label="管理中心"></el-table-column>
            <el-table-column property="road_name" label="路段名称"></el-table-column>
            <el-table-column property="type" label="类型">
                <template slot-scope="{ row }">
                    <!-- {{ row.type == 1 ? '收费站' : '服务区' }} -->
                    {{ comType(row.type) }}
                </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度">
            </el-table-column>
            <el-table-column prop="latitude" label="纬度">
            </el-table-column>
            <el-table-column align="center" label="生成二维码">
                <template slot-scope="{row}">
                    <el-button icon="el-icon-s-marketing" type="warning" @click.stop="createEWM(row)">生成二维码</el-button>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="{ row }">
                    <el-button type="success" style="margin: 5px;" @click="edit(row)">编辑</el-button>
                    <el-button type="warning" style="margin: 5px;" @click="delgridData(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加收费站 -->
        <el-dialog :title="addTitle" :visible.sync="dialogFormVisible" width="60%" @close="formReset" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
                <el-row type="flex" :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="收费站/服务区名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入收费站/服务区名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="管理中心" prop="admin_id">
                            <el-select v-model="form.admin_id" placeholder="请选择">
                                <el-option v-for="item in adminUser" :key="item.id" :label="item.nickname" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="类型" prop="type">
                            <el-select v-model="form.type" placeholder="请选择类型">
                                <el-option label="收费站" :value="1"></el-option>
                                <el-option label="服务区" :value="2"></el-option>
                                <el-option label="养护所" :value="3"></el-option>
                                <el-option label="养护站" :value="4"></el-option>
                                <el-option label="清障救援大队" :value="5"></el-option>
                                <el-option label="信息分中心" :value="6"></el-option>
                                <el-option label="清障救援中队 " :value="7"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择路段" prop="road_id">
                            <el-select v-model="form.road_id" placeholder="请选择路段" filterable>
                                <el-option v-for="item in roadSectionList" :key="item.id" :label="item.road_name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <div style="height:500px">
                            <mapQQ ref="mapQQ" :location.sync="form.location"></mapQQ>
                        </div>
                    </el-col>
                    <el-row type="flex" justify="center" style="margin-top:20px;width:100%">
                        <el-button type="primary" @click="addgridData('ruleForm')" style="margin-right:30px">确 认</el-button>
                        <el-button @click="dialogFormVisible = false" type="primary">取 消</el-button>
                    </el-row>
                </el-row>
            </el-form>
        </el-dialog>
        <el-pagination class="main-pagination" :total="total" :current-page.sync="page" :page-size="limit" layout="prev, pager, next, jumper,total" @current-change="getInfo" hide-on-single-page></el-pagination>
    </div>
</template>

<script>
import { post } from "@/assets/js/http.js"
export default {
    components: {
        "el-upload-file": () => import("@/components/el-upload-file.vue"),
        "mapQQ": () => import("@/components/map/index.vue"),

    },
    data() {
        return {
            addTitle: "添加收费站/服务区",
            total: 0,
            limit: 20,
            page: 1,
            keyword: "",
            admin_id: "",
            data: [],
            dialogFormVisible: false,
            adminUser: [],
            managementCenter: [],
            importindex: [],
            roadSectionList: [],
            roadNumberList: [],
            role: localStorage.getItem("role"),
            form: {
                name: '',
                type: '',
                road_id: "",
                admin_id: "",
                location: null
            },
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                type: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                road_id: [
                    { required: true, message: '请选择路段', trigger: 'change' }
                ],
                admin_id: [
                    { required: true, message: '请选择路段', trigger: 'change' }
                ],
            },
            // props: {
            //     label: "nickname",
            //     value: "id",
            //     lazy: true,
            //     async lazyLoad(node, resolve) {
            //         const { level, value } = node;
            //         if (level === 0) {
            //             const result = await post({
            //                 url: "/admin/answer.Road/admin_user",
            //                 data: {}
            //             });
            //             console.log(result, 'result')
            //             resolve(result);
            //         } else if (level === 1) {
            //             const result = await post({
            //                 url: "/admin/answer.Road/index",
            //                 data: {
            //                     admin_id: value,
            //                     limit: 50,
            //                 }
            //             });

            //             result.data.forEach((item) => {
            //                 item.leaf = true
            //                 item.nickname = item.road_name
            //             });
            //             console.log(result)
            //             resolve(result.data);
            //         }
            //     },
            // },
        }
    },
    methods: {
        getInfo(index = 1) {
            post({
                url: '/admin/answer.Road/act_road',
                data: {
                    page: index,
                    limit: this.limit,
                    keyword: this.keyword,
                    admin_id: this.admin_id
                    // road_id: this.admin_id[1] || ""
                },
                loading: true
            }).then(res => {
                console.log(res);
                // this.page =
                this.total = res.total
                this.page = res.current_page
                this.data = res.data
            })
        },

        //  获取管理中心
        getAdminUser() {
            post({
                url: "/admin/answer.Subject/admin_list"
            }).then(res => {
                this.adminUser = res
            })
        },
        // 获取路段
        getRoadSection() {
            post({
                url: "/admin/answer.Road/index",
                data: {
                    limit: 999
                }
            }).then(res => {
                console.log(res, "sssssssssss");
                this.roadSectionList = res.data

            })
        },
        //  获取路段编号
        getRoadNumber() {
            post({
                url: "/admin/answer.Road/road_number"
            }).then(res => {
                this.roadNumberList = res
            })
        },
        // 添加收费站
        add() {
            this.addTitle = "添加收费站/服务区"
            this.dialogFormVisible = true
        },
        // 编辑收费站
        edit(row) {
            this.addTitle = "修改收费站/服务区"
            this.dialogFormVisible = true
            this.form = {
                ...row, ...{
                    location: {
                        lat: row.latitude,
                        lng: row.longitude
                    }
                }
            }
        },
        // 表單提交
        addgridData(formName) {
            let longitude = this.form.location.lng
            let latitude = this.form.location.lat
            this.form.nickname = this.form.nickname ? this.form.nickname : ""
            this.form.road_name = this.form.road_name ? this.form.road_name : ""
            let datasList = JSON.parse(JSON.stringify(this.form))
            datasList.longitude = longitude
            datasList.latitude = latitude
            if (!latitude) {
                this.$message('请选择一个坐标');
                return
            }

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    post({
                        url: '/admin/answer.Road/act_edit',
                        data: datasList,
                        loading: true,
                        successTip: true
                    }).then(res => {
                        this.dialogFormVisible = false
                        this.getInfo()
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删除收费站
        delgridData(row) {
            this.$confirm('此操作将永久删除该收费站/服务区, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                post({
                    url: "/admin/answer.Road/act_del",
                    data: {
                        id: row.id
                    },
                    loading: true,
                    successTip: true,
                }).then(res => {
                    this.getInfo(this.page)
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 生成二維碼
        createEWM(row) {
            post({
                url: "/admin/answer.Road/createQrcode_road",
                data: { id: row.id, admin_id: row.admin_id }
            }).then(res => {
                console.log(res);
                open("http://" + res.qrcode_url)
                // let a = document.createElement("a"); //创建一个a元素
                // a.href = res.qrcode_url;    //a元素图片地址
                // a.download = "二维码"; //图片名
                // a.click()
                // let url = res.qrcode_url
                // let image = new Image()
                // const download = (url) => {
                //     let a = document.createElement('a');
                //     a.download = "下载";
                //     a.href = url;
                //     a.click()
                // }
                // image.setAttribute('crossOrigin', 'anonymous');
                // image.src = "http://" + url;
                // image.onload = () => {
                //     let canvas = document.createElement('canvas')
                //     canvas.width = image.width
                //     canvas.height = image.height
                //     let ctx = canvas.getContext('2d')
                //     ctx.drawImage(image, 0, 0, image.width, image.height)
                //     canvas.toBlob((img) => {
                //         var imgUrl = URL.createObjectURL(img);
                //         download(imgUrl)
                //     })
                // }
            })
        },
        // 表单关闭回调
        formReset() {
            this.form = Object.assign({}, this.$options.data().form)
        },
        // 下载导入模板
        importTemplate() {
            post({
                url: "admin/answer.Road/import_formwork"
            }).then(res => {
                open(res.url)
            })
        },
        // 导入
        getImportData() {
            console.log(this.importindex[0]?.url);
            post({
                url: "/admin/answer.Road/import_road",
                data: {
                    file: this.importindex[0].url
                }
            }).then(res => {
                this.getInfo()
            }).finally(() => {
                this.importindex = []
            })
        },
        // 重置
        reset() {
            this.admin_id = ""
            this.keyword = ""
            this.getInfo()
        }
    },
    computed: {
        comType() {
            return (type) => {
                switch (type) {
                    case 1:
                        return "收费站"
                    case 2:
                        return "服务区"
                    case 3:
                        return "养护所"
                    case 4:
                        return "养护站"
                    case 5:
                        return "清障救援大队"
                    case 6:
                        return "信息分中心"
                    case 7:
                        return "清障救援中队"
                }
            }
        }
    },
    mounted() {
        this.getInfo()
        this.getRoadSection()
        // this.getRoadNumber()
        this.getAdminUser()
    }
}
</script>

<style lang="scss" scoped>
.aclass {
    text-decoration: none;
    color: #fff;
}
</style>